import { defineStore } from 'pinia'
import { ShopInfoStore } from './state'
import Storage from '@/utils/storage'
import shopInfo from './state'

export const useShopInfoStore = defineStore('shopStore', {
    state: () => Storage.get('shopStore') || shopInfo || {},
    actions: {
        SET_SHOP_INFO(payload: ShopInfoStore) {
            this.shopInfo = { ...this.shopInfo, ...payload }
            Storage.set('shopStore', this.shopInfo, 60 * 60 * 24)
        },
        DEL_SHOP_INFO() {
            this.shopInfo = {
                id: '',
                logo: '',
                name: '',
                newTips: '',
                status: '',
                token: '',
                refresh_token: '',
                userId: '',
                nickname: '',
                mode: '',
            }
            Storage.remove('shopStore')
        },
        SET_SHOP_TOKEN(payload: { access_token: string; refresh_token: string }) {
            this.shopInfo.token = payload.access_token
            this.shopInfo.refresh_token = payload.refresh_token
            Storage.set('shopStore', this.shopInfo, 60 * 60 * 24)
            return payload.access_token
        },
        SET_SHOP_Id(id: string) {
            this.shopInfo.id = id
            Storage.set('shopStore', this.shopInfo, 60 * 60 * 24)
            return id
        },
        SET_SHOP_ADMIN_DATA(payload: any) {
            this.shopInfo = Object.assign(this.shopInfo, payload)
            Storage.set('shopStore', this.shopInfo, 60 * 60 * 24)
        },
    },
    getters: {
        getterShopInfo: (state) => {
            return getShopInfoFn(state)
        },
    },
})
function getShopInfoFn(state: any) {
    if (judgeNotEmpty(state.shopInfo)) {
        const shopInfo = Storage.get('shopStore')
        console.log(shopInfo, 'shopInfo')
        if (judgeNotEmpty(shopInfo)) {
            return { id: '', token: '' }
        } else {
            state.shopInfo = shopInfo
            return shopInfo
        }
    } else {
        return state.shopInfo
    }
}
/**
 * 判断shopInfo是否为空
 */
function judgeNotEmpty(shopInfo: any) {
    if (JSON.stringify(shopInfo) === '{}' || shopInfo === null || shopInfo === undefined) return true
    if (Object.keys(shopInfo).length === 0) return true
    if (!shopInfo.id) return true
    return false
}
